package com.mmall.concurrency.example.atomic;

import com.mmall.concurrency.annoations.ThreadSafe;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 模拟并发，需要用到信号量来模拟同时200个并发，用CountDownLatch来模拟计数，一共有多少个请求
 */
@Slf4j
@ThreadSafe
public class AtomicExample5 {

	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

	private static AtomicIntegerFieldUpdater<AtomicExample5> updater =
            AtomicIntegerFieldUpdater.newUpdater(AtomicExample5.class, "count");

    public volatile int count = 100; // 字段必须是volatile修饰，并且非static才可以

    public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public static void main(String[] args) {
        AtomicExample5 example5 = new AtomicExample5();

        if (updater.compareAndSet(example5, 100, 120)){
            log.info("update success 1, {}", example5.getCount());
        }
        if (updater.compareAndSet(example5, 100, 120)){
            log.info("update success 2, {}", example5.getCount());
        }else{
            log.info("update fail, {}", example5.getCount());
        }

    }

}
